package com.yiban.demo.LoginUser.Controller;

import com.yiban.demo.Global.Entity.ResponseEntity;
import com.yiban.demo.LoginUser.Entity.BiPassword;
import com.yiban.demo.LoginUser.Entity.InvitationCode;
import com.yiban.demo.LoginUser.Entity.LoginUserPO;
import com.yiban.demo.LoginUser.Entity.LoginUserVO;
import com.yiban.demo.LoginUser.Service.LoginUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Optional;
import java.util.function.BiFunction;

@RestController
@RequestMapping("/User")
public class LoginUserController {
    public static final String USER_SESSION_KEY = "user";

    @Autowired
    private LoginUserService loginUserService;

    @PostMapping("/loginIn")
    public ResponseEntity<LoginUserVO> loginIn(@Validated @RequestBody LoginUserVO loginUserVO, HttpSession httpSession){
        LoginUserPO userPO = loginUserService.loginIn(loginUserVO);
        if (userPO == null){
            return ResponseEntity.Failure("请检查用户名和密码");
        }
        httpSession.setAttribute(USER_SESSION_KEY,userPO);
        return ResponseEntity.Success(loginUserService.transToLoginVo(userPO));
    }

    @PostMapping("/register")
    public ResponseEntity<LoginUserVO> register(@Validated @RequestBody LoginUserVO loginUserVO,HttpSession httpSession,@RequestHeader("invitation_code") String invitationCode){
        if (!loginUserService.userInvitationCode(invitationCode)) {
            return ResponseEntity.Failure("邀请码无效");
        }
        return Optional.ofNullable(loginUserService.register(loginUserVO))
                .map((p) -> {
                    httpSession.setAttribute(USER_SESSION_KEY, p);
                    return ResponseEntity.Success(loginUserService.transToLoginVo(p));
                })
                .orElse(ResponseEntity.Failure("用户名重复"));
    }
    @DeleteMapping("/loginOut")
    public ResponseEntity<Void> loginOut(HttpSession httpSession){
        httpSession.removeAttribute(USER_SESSION_KEY);
        return ResponseEntity.Success(null);
    }

    @PutMapping("/password")
    public ResponseEntity<Boolean> modifyPassword(@RequestBody @Validated BiPassword biPassword, HttpSession httpSession){
        LoginUserPO loginUserPO = (LoginUserPO) httpSession.getAttribute(USER_SESSION_KEY);
        if (loginUserService.modifyPassword(loginUserPO,biPassword.getOldPassword(),biPassword.getNewPassword())) {
            loginUserPO.setPassword(biPassword.getNewPassword());
            return ResponseEntity.Success(true);
        }else {
            return ResponseEntity.Failure("旧密码有误");
        }
    }
    @GetMapping("/invitationCode")
    public ResponseEntity<InvitationCode> getInvitatioCode(){
        return ResponseEntity.Success(loginUserService.getNewInvitationCode());
    }






}
